package whf.framework.util.trans;

import java.sql.Connection;

import javax.sql.DataSource;

import whf.framework.exception.AppException;
import whf.framework.resource.db.ConnectionManager;

/**
 * @author wanghaifeng
 * @create Jan 4, 2007 4:32:34 PM
 * 
 */
public abstract class CallbackTransactionObject {
	private ConnectionManager cm;
	private DataSource ds;
	
	public CallbackTransactionObject(ConnectionManager cm){
		if(cm == null) throw new IllegalArgumentException("ConnectionManager is null");
		this.cm = cm;
	}
	
	public CallbackTransactionObject(DataSource ds){
		if(cm == null) throw new IllegalArgumentException("DataSource is null");
		this.ds = ds;
	}
	
	public abstract void handleBusinese(Connection con) throws AppException;
	
	public void handle() throws TransactionException{
		Connection con = null;
		try{
			try{
				con = this.getConnection();
				con.setAutoCommit(false);
				this.handleBusinese(con);
				con.commit();
			} catch (Exception e){
				con.rollback();
				throw e;
			} finally{
				if(con != null){
					con.close();
				}
			}
		}catch(Exception e){
			throw new TransactionException(e);
		}
	}
	
	private Connection getConnection() throws Exception{
		if(cm != null){
			return cm.getPooledConnection();
		} else if(ds != null){
			return ds.getConnection();
		}
		return null;
	}
}
